﻿using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Controls;

using Poet.Views;

namespace Poet
{
    /// <summary>
    /// Interaction logic for MultiSelectComboBox.xaml
    /// </summary>
    public partial class MultiComboBox
    {
        public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.Register(
            "SelectedItems", typeof(IEnumerable), typeof(MultiComboBox), new PropertyMetadata());

        public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register(
            "Items", typeof(IEnumerable), typeof(MultiComboBox), new PropertyMetadata(ItemsChanged));

        public MultiComboBox()
        {
            InitializeComponent();
        }

        public IEnumerable SelectedItems
        {
            get
            {
                return (IEnumerable)GetValue(SelectedItemsProperty);
            }
            set
            {
                SetValue(SelectedItemsProperty, value);
            }
        }

        public IEnumerable Items
        {
            get
            {
                return (ObservableCollection<DocumentView>)GetValue(ItemsProperty);
            }
            set
            {
                SetValue(ItemsProperty, value);
            }
        }

        private IList SelectedItemsCollection
        {
            get
            {
                return SelectedItems as IList;
            }
        }

        private static void ItemsChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
        {
            var collection = args.NewValue as INotifyCollectionChanged;
            var @this = dependencyObject as MultiComboBox;
            if (@this != null && collection != null)
            {
                @this.ComboBox.ItemsSource = collection as IEnumerable;
                collection.CollectionChanged += @this.ItemsOnCollectionChanged;
            }
        }

        private void ItemsOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.OldItems != null)
            {
                foreach (var oldItem in e.OldItems)
                {
                    SelectedItemsCollection.Remove(oldItem);
                }
            }
        }

        private void ToggleButton_OnCheckChanged(object sender, RoutedEventArgs e)
        {
            var checkBox = sender as CheckBox;
            if (checkBox == null || SelectedItems == null)
            {
                return;
            }

            var item = checkBox.DataContext;
            if(checkBox.IsChecked == true)
            {
                SelectedItemsCollection.Add(item);
            }
            else
            {
                SelectedItemsCollection.Remove(item);
            }
        }
    }
}
